<template>
    <div>
      <el-dialog :title="data.titleName" v-model="data.children_page" :close-on-click-modal='false'
       :append-to-body='true' width="800px">
        <el-form ref="ruleFormRef" :rules="rules" :model="ruleForm" label-width="150px">
          <!-- <el-form-item v-if="data.isAdd" label="所属系统：" prop="system">
            <el-select v-model="ruleForm.system" @change="changeSystem" placeholder="请选择" style="width:300px;">
              <el-option v-for="item in data.systems" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="角色名称：" prop="username">
            <el-input v-model.trim="ruleForm.username" style="width:300px;" />
          </el-form-item>
          <el-form-item label="手机号：" prop="mobile">
            <el-input v-model.trim="ruleForm.mobile" style="width:300px;" /> 
          </el-form-item>
          <el-form-item label="邮箱：" prop="email">
            <el-input v-model.trim="ruleForm.email" style="width:300px;" /> 
          </el-form-item>


          <!-- <h1>{{test1}}测试1</h1>
  <h1>{{test2}}测试2</h1> -->

          <el-form-item label="用户头像" prop="avatar">
        <UploadImg v-model:image-url="ruleForm!.avatar" v-model:test2="ruleForm.avatarurl"  v-model="test1"  :file-size="3" height="140px" width="140px" border-radius="50%">
          <template #empty>
            <span>请上传头像</span>
          </template>
          <template #tip> 头像大小不能超过 3M </template>
        </UploadImg>
      </el-form-item>
      
          <el-form-item label="状态"  style="width:300px;">
            <el-switch v-model="ruleForm.status" active-text="开启" active-value="normal" inactive-value="hidden" active-color="#13ce66">
            </el-switch>
          </el-form-item>
          <!-- <el-form-item label="菜单配置：">
            <div class="jurisdiction-border">
              <el-tree show-checkbox :data="data.treeDatas" node-key="id" ref="treeRef" :check-strictly="true"
                :default-checked-keys="data.nowKeys">
                <template #default="{ node, data }">
                  <span class="custom-tree-node">
                    <span v-if="data.type == 0||data.type == 1">
                      <el-tag :type="data.flag=='app'?'success':''" size="small"> {{data.flag=='app'?'app-菜单':'pc-菜单'}}
                      </el-tag>
                      <span :title="data.name" class='tree-name-leave'> {{data.name}} </span>
                    </span>
                    <span v-else>
                      <el-tag type="warning" size="small"> {{data.flag}}-按钮 </el-tag>
                      <span :title="data.name" class='tree-name-leave'> {{data.name}} </span>
                    </span>
                  </span>
                </template>
              </el-tree>
            </div>
          </el-form-item> -->
          <el-form-item>
            <el-button @click="data.children_page = false">取 消</el-button>
            <el-button type="primary" @click="onSubmit(ruleFormRef)">确 定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </template>
  <script lang="ts" setup>
import UploadImg from "./Upload/Img.vue";
    import {
      roleInsert,
      roleUpdate,
      menuAll,
      menuRole,
    } from '../../../api/index';
    import {
      ElMessage,
      ElTree
    } from "element-plus";
    // import type { FormInstance } from 'element-plus' 
    import {
      ref,
      reactive,
      nextTick,
      // defineProps,//defineProps声明props;具备完整的类型推断;<script setup>直接可用
      // defineEmits,//defineEmits声明事件;具备完整的类型推断;<script setup>直接可用
      // defineExpose//暴露出去;<script setup>直接可用
    } from 'vue';
import { log } from "console";



    const test1 = ref('')
const test2 = ref('')
// const test1=(v:any)=>{
//   console.log("接收到子组件的值",v)
//   alert(2);
// }
    const ruleFormRef = ref();//表单ref
    //获取tree选中的值
    const treeRef = ref < InstanceType < typeof ElTree >> ();
    const emit = defineEmits(["onItemChange"]);//声明事件(父级页面上添加的 @监听事件)
 
    //数据双向绑定;复杂类型数据=>响应式数据
    const data = reactive({
      titleName: '',
      checkAll: false,
      children_page: false,
      isAdd: false,
      systems: [{
        name: '开发1部',
        id: 'water'
      }, {
        name: '市场部',
        id: 'pollution'
      }],
      nowKeys: [] as any[], // 属性需要做类型断言处理 //树-选中数据
      treeDatas: [], //树-总数据
      id: '',
    });
    //ts类型断言
    //定义类型
    interface User {
      name: string
      type: string
      key: string
      id: string
      username: string
      avatar: string
      avatarurl:string
      email: string
      mobile: string
      status:string
    };
    const ruleForm = reactive({
      
 
      system:"",
      username: "",
      avatar: "",
      avatarurl:"",
      email: "",
      mobile: "",
      status:"",
    });
    const rules = ref({
      username: [{
          required: true,
          message: '请输入角色名称',
          trigger: 'blur'
        },
        {
          min: 1,
          max: 50,
          message: '长度在 1 到 50 个字符',
          trigger: 'blur'
        }
      ],
      
    });
    //父调子的子
    const addItemShow = (now_name: string) => {
      data.titleName = '添加角色';
      data.children_page = true;
      data.isAdd = true;
      ruleForm.username = '';
        ruleForm.avatar = '';
        ruleForm.avatarurl = '';
        ruleForm.email = '';
        ruleForm.mobile = '';
        ruleForm.status = '';
      data.nowKeys = []; //树-选中数据
      getTree();
      nextTick(() => {
      ruleFormRef.value.resetFields();//重置表单
      })
    };
    //父调子的子
    const addItemShow2 = (row: User, now_name: string) => {
      data.titleName = '编辑角色';
      data.children_page = true;
      data.isAdd = false;
      nextTick(() => {
        ruleFormRef.value.resetFields();//重置表单
        ruleForm.username = row.username;
        ruleForm.avatar = row.avatar;
        ruleForm.avatarurl = row.avatarurl;
        ruleForm.email = row.email;
        ruleForm.mobile = row.mobile;
        ruleForm.status = row.status;
        data.id = row.id;
        data.nowKeys = [] //树-选中数据
        data.treeDatas = [] //树-总数据
        menuRoleGet()
      })
    };
    //回显树-选中数据
    const menuRoleGet = () => {
      let params = {
        id: data.id,
      }
      menuRole(params).then(res => {
        if (res.status == 200) {
          if (res.data.list.length != 0) {
            for (var i in res.data.list) {
              data.nowKeys.push(res.data.list[i].id)
            }
          }
          getTree()
        } else if (res.status  !==200) {
          ElMessage.error(res.data.msg);
        }
      })
    };
    //改变系统时=>获取树数据
    const changeSystem = () => {
      getTree();
    };
    //获取树数据
    const getTree = () => {
      data.treeDatas = [];
      let params = {
        systemFlag: ruleForm.system,
      }
      menuAll(params).then(res => {
        if (res.status == 200) {
          data.treeDatas = res.data.list
        } else if (res.status  !== 200) {
          ElMessage.error(res.statusText);
        }
      })
    };
    //添加/修改   : FormInstance | undefined
    const onSubmit = async (formEl:any) => {
      if (!formEl) return
      formEl.validate((valid:any) => {
        if (valid) {
          if (data.isAdd) { 
            addRoles();
          } else {
            changeRoles();
          }
        } else {
          return false;
        }
      });
    };




 



// ref的作用是实现响应式， 如果没有ref则不能实现响应式（引用数据类型用reactive）
          // 使用ref包裹的数据，需要通过 .value 的形式访问他的值
    const addRoles = () => { 
      let params = {
        action: 'apiadd',
        username: ruleForm.username,
        avatar: ruleForm.avatarurl,
        status: ruleForm.status,
        mobile: ruleForm.mobile,
        email: ruleForm.email,
        // menuIds: treeRef.value!.getCheckedKeys(false),
      }
      roleInsert(params).then(res => {
        console.log(267);
        
        if (res.status == 200) {
          ElMessage({
            showClose: true,
            message: '操作成功',
            type: 'success',
          })
          data.children_page = false;
          emit("onItemChange");
        } else if (res.status  !== 200) {
          ElMessage.error(res.statusText);
        }
      })
    };
    //修改接口
    const changeRoles = () => {
      console.log(284);
      let params = {
        action: 'apiedit',
        id: data.id,
        username: ruleForm.username,
        avatar: ruleForm.avatarurl,
        status: ruleForm.status,
        mobile: ruleForm.mobile,
        email: ruleForm.email,
        // menuIds: treeRef.value!.getCheckedKeys(false),
      }
      roleUpdate(params).then(res => {
        console.log(296);
        console.log(res)
        console.log(res.status)
        if (res.status == 200) {
          ElMessage({
            showClose: true,
            message: '操作成功',
            type: 'success',
          })
          data.children_page = false;
          emit("onItemChange");
        } else if (res.status  !== 200) {
          ElMessage.error(res.statusText);
        }
      })
    };
    defineExpose({
      addItemShow,
      addItemShow2
    }) //将子组件方法暴露出来，让父组件调用
  </script>
  <style scoped>
    .jurisdiction-border {
      width: 500px;
      height: 300px;
      padding: 10px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      overflow: auto;
    }
   
    .jurisdiction-border::-webkit-scrollbar {
      width: 7px;
      height: 7px;
      background-color: rgb(241, 241, 241);
      border-radius: 3px;
    }
   
    .jurisdiction-border::-webkit-scrollbar-thumb {
      background-color: rgb(193, 193, 193);
      border-radius: 3px;
    }
   
    .tree-name-leave {
      margin-leave: 5px;
    }
  </style>
  <style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>